import 'package:get/get.dart';
import 'package:web_socket_channel/status.dart' as status;
import 'package:web_socket_channel/web_socket_channel.dart';

/*
web_socket_channel: ^3.0.1
* */

class WebSocket {
  static late WebSocketChannel _channel;
  static var isConnected = false.obs;

  static Future<void> connect(String url, {required Function onReceiveMsg, Function? onClose}) async {
    try {
      _channel = WebSocketChannel.connect(Uri.parse(url));
      await _channel.ready;
      print('[B] Websocket 已连接');
      isConnected.value = true;
      _channel.stream.listen((message) {
        print('[B] Websocket 收到消息：$message');
        onReceiveMsg?.call(message);
      }, onError: (error) {
        throw Exception('[B] $error');
      }, onDone: () {
        print('[B] Websocke 已断开');
        onClose?.call();
      });
    } catch (e) {
      isConnected.value = false;
      throw Exception('[B] $e');
    }
  }

  static void send(String message) {
    if (isConnected.value) {
      print('[B] Websocket 发送消息：$message');
      _channel.sink.add(message);
    }
  }

  static void disconnect() {
    if (isConnected.value) {
      _channel.sink.close(status.goingAway);
      isConnected.value = false;
      print('[B] Websocke 已断开');
    }
  }
}
